#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>

/*
    About linklist have head node, review
*/

typedef struct node{
    int data;
    struct node *next;
}Node;

typedef struct {
    Node *head, *tail;
    int length;
}Linklist;

//declare
void Insert_back(Linklist *L,int data);
Node* _buyNode(int data);
void Initlist(Linklist *L);
void CreateList_head(Linklist *L, int n);
void PrintList_h(Linklist L);

void Initlist(Linklist *L) {
    L->head = (Node*)malloc(sizeof(Node));
    L->head = L->tail;
    L->tail->next= NULL;
    L->length = 0;
    printf("list inited.\n");
}

void CreateList_head(Linklist *L, int n) {
    Initlist(L);
    int data;
    printf("input %d data:\n", n);
    for(int i = 0; i < n; i++) {
        scanf("%d", &data);
        Insert_back(L, data);
        Node *p = _buyNode(data);
    }
    printf("created.\n");
}

Node* _buyNode(int data) {
    Node *p = (Node*)malloc(sizeof(Node));
    p->next = NULL;
    p->data = data;
    return p;
}

void Insert_front(Linklist *L, int data) {
    assert(L);
    Node *p = _buyNode(data);
    //insert
    p->next = L->head->next;
    L->head->next = p;
    L->length++;
}

void Insert_back(Linklist *L,int data) {
    assert(L);
    Node *p = _buyNode(data);
    //insert
    L->tail->next = p;
    L->tail = p;
    L->length++;
}

void remove_h(Linklist *L, int data) {
    Node *p, *q;
    p = L->head->next;
    if(p->data == data) {
        L->head->next = p->next;
        p->next = NULL;
        free(p);
        return;
    }
    while(p->next != NULL) {
        q = p->next;
        if(q->data = data) {
            p->next = q->next;
            q->next = NULL;
            free(q);
            return;
        }
        p = p->next;
    }
}

void PrintList_h(Linklist L) {
    if(L.length == 0) {
        printf("list is empty!\n");
        return;
    }
    printf("linklist Below:\n");
    Node *p = L.head->next;
    for(int i = 0; i < L.length; i++) {
        printf("%d ", p->data);
        p = p->next;
    }
}

int main(int argc, char const *argv[])
{
    Linklist L;
    int len;
    printf("input n:\n");
    scanf("%d", &len);
    // Initlist(&L);
    CreateList_head(&L, len);
    PrintList_h(L);

    printf("\nnow Insert 5\n");
    Insert_front(&L, 5);
    PrintList_h(L);

    remove_h(&L, 5);
    PrintList_h(L);
    return 0;
}


